package com.geekjam.dingdongandroid;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.*;
import com.geekjam.dingdongandroid.Tab.AlarmTab;
import com.geekjam.dingdongandroid.Tab.MessageTab;
import com.geekjam.dingdongandroid.api.DingDongMessageProxy;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Calendar;

/**
 * by SEGFault Xiawei
 * Date: 3/9/13 Time: 5:35 PM
 */
public class DingDongApp extends Activity {
    public static final int ALARM = 0;
    public static final int MESSAGE = 1;
    private ViewAnimator viewAnimator;
    private MessageTab messageTab;
    private PendingIntent pendingIntent;
    private static final long EVERY_DAY = 24*60*60*1000;
    private MediaRecorder mRecorder;

    private static String mFileName = DingDongMessageProxy.RECORD_FILENAME;
    private final static String LOG_TAG = "HOME_SCREEN";

    View.OnClickListener alarmOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            openTimePickerDialog(true);
        }
    };
    View.OnClickListener alarmOffClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageView alarmIcon = ((ImageView)findViewById(R.id.alarm_icon));
            alarmIcon.setImageResource(R.drawable.alarm_red_1_8cm);
            ((AlarmManager) getSystemService(ALARM_SERVICE)).cancel(pendingIntent);
            alarmIcon.setOnClickListener(alarmOnClickListener);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        viewAnimator = (ViewAnimator) findViewById(R.id.view_animator);

        messageTab = new MessageTab(getApplicationContext(), viewAnimator);
        viewAnimator.addView(messageTab, MESSAGE);

        setOnClickListener();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 && viewAnimator.getDisplayedChild()!=DingDongApp.ALARM) {
            viewAnimator.setDisplayedChild(DingDongApp.ALARM);
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    private void setOnClickListener() {
        ImageView messageIcon = (ImageView) findViewById(R.id.message_icon);

        messageIcon.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                if (action == MotionEvent.ACTION_DOWN) {
                    ((ImageView)findViewById(R.id.alarm_icon)).setVisibility(View.INVISIBLE);
                    findViewById(R.id.record_tips).setVisibility(View.VISIBLE);
                    startRecording();
                } else if (action == MotionEvent.ACTION_UP){
                    findViewById(R.id.alarm_icon).setVisibility(View.VISIBLE);
                    findViewById(R.id.record_tips).setVisibility(View.INVISIBLE);
                    stopRecording();
                    viewAnimator.setDisplayedChild(MESSAGE);
                }
                return true;
            }
        });

        ImageView alarmIcon = (ImageView) findViewById(R.id.alarm_icon);
        alarmIcon.setOnClickListener(alarmOnClickListener);
    }

    private void startRecording() {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed" + e.getMessage());
        }

        mRecorder.start();
    }

    private void stopRecording() {
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;
    }

    private long getMillisUntilAlarm(int hour, int minute) {
        Calendar current = Calendar.getInstance();
        Calendar alarmSet = (Calendar) current.clone();
        alarmSet.set(Calendar.HOUR_OF_DAY, hour);
        alarmSet.set(Calendar.MINUTE, minute);
        alarmSet.set(Calendar.SECOND, 0);
        alarmSet.set(Calendar.MILLISECOND, 0);

        if(alarmSet.compareTo(current) <= 0){
            alarmSet.add(Calendar.DATE, 1);
        }
        return alarmSet.getTimeInMillis();
    }

    @Override
    protected void onPause() {
        messageTab.finalize();
        super.onPause();
    }

    TimePickerDialog timePickerDialog;

    private void openTimePickerDialog(boolean is24r){
        Calendar calendar = Calendar.getInstance();
        TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                Intent myIntent = new Intent(DingDongApp.this, ScheduledAlarmReceiver.class);
                pendingIntent = PendingIntent.getBroadcast(DingDongApp.this, 0, myIntent, 0);
                DingDongMessageProxy.getRandomSound(new DingDongMessageProxy.OnGetRandomSoundComplete() {
                    @Override
                    public void succeeded() {
                        //To change body of implemented methods use File | Settings | File Templates.
                    }

                    @Override
                    public void failed(Throwable e, JSONObject response) {
                        //To change body of implemented methods use File | Settings | File Templates.
                    }
                });
                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                long millisUntilAlarm = getMillisUntilAlarm(hourOfDay, minute);
                //TODO for demo
                millisUntilAlarm = System.currentTimeMillis() + 10000;
                //--------------------
                alarmManager.set(AlarmManager.RTC_WAKEUP, millisUntilAlarm, pendingIntent);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, millisUntilAlarm, EVERY_DAY, pendingIntent);
                ImageView alarmIcon = ((ImageView)findViewById(R.id.alarm_icon));
                alarmIcon.setImageResource(R.drawable.green1);
                alarmIcon.setOnClickListener(alarmOffClickListener);
                Toast.makeText(DingDongApp.this, "Start Alarm", Toast.LENGTH_LONG).show();
            }
        };

        timePickerDialog = new TimePickerDialog(
                DingDongApp.this,
                onTimeSetListener,
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                is24r);
        timePickerDialog.setTitle("Set Alarm Time");
        timePickerDialog.show();
    }
}
